<!-- eslint-disable no-unused-expressions -->
<!-- eslint-disable radix -->
<!-- eslint-disable no-useless-escape -->
<!-- eslint-disable no-param-reassign -->
<!--
 * @Description: Description
 * @Author: Kerwin
 * @Date: 2023-10-13 11:41:12
 * @LastEditTime: 2024-08-09 15:33:53
 * @LastEditors:  Please set LastEditors
-->
<!-- eslint-disable no-shadow -->
<!-- eslint-disable no-console -->
<!-- eslint-disable no-use-before-define -->
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { baseApi, moneyApi, powerBankApi, userApi } from '@/api'
import { checkLoginState, getImgFullPath } from '@/utils/index'
import { useUserStore, useConfigStore } from '@/store'
import {
  browserVersion,
  compareVersion,
  qs,
  getQueryVariable,
  launchClientApp,
  route,
  isWeChat
} from '@/utils/common'
import c_topUp from '@/packageB/pages/carWash/c_topUp.vue'

const userStore = useUserStore()
const configStore = useConfigStore()
const { userInfo, hasLogin } = storeToRefs(userStore)
const deviceInfo = ref({})
const siteInfo = ref({})
const deviceSn = ref('hy000005')
const serviceType = ref(powerBankApi.serviceType.WASH)
const loading = ref(false)
const checked = ref(false)
const show = ref(false)
const configDetails = ref([])
const selectedConfig = ref({})
function showSelect() {
  show.value = true
}
function confirm(e: { value: any }[]) {
  const { value } = e[0]
  selectedConfig.value =
    configDetails.value.find((item) => item.type === value) || {}
}

async function getDetail() {
  if (!deviceSn.value) return
  uni.showLoading({
    mask: true
  })
  const { data } = await powerBankApi
    .getDeviceDetail({
      deviceSn: deviceSn.value
    })
    .finally(() => {
      uni.hideLoading()
    })
  deviceInfo.value = data?.device
  siteInfo.value = data?.site
}

const outOrderNo = ref('')
const paymentSubType = ref(4) // h5=4，app=11
// 启动设备
async function start(params?: { paymentType?: any; cardId?: any }) {
  uni.showLoading({
    title: '启动中'
  })
  loading.value = true
  const obj = {
    deviceSn: deviceSn.value,
    serviceType: serviceType.value,
    consumeType: selectedConfig.value.type,
    paymentType: params?.paymentType || 1,
    paymentSubType: paymentSubType.value,
    paymentId: outOrderNo.value
  }
  if (params?.cardId) {
    obj.cardId = params.cardId
  }
  const { code, message } = await powerBankApi.deviceStart(obj).finally(() => {
    loading.value = false
    uni.hideLoading()
  })
  if (code === 0) {
    uni.showModal({
      title: '提示',
      content: message,
      showCancel: false,
      confirmText: '确认',
      success: async ({ confirm }) => {
        if (confirm) {
          await getOrderInProgress()
          await jumpToOrderDetail()
        }
      }
    })
  } else {
    uni.showModal({
      title: '提示',
      content: message,
      showCancel: false,
      confirmText: '确认'
    })
  }
}
const userBalance = ref(0)
const useTimesAmount = ref(0)
const cards = ref([])
async function getOrderConsumeType() {
  if (!deviceSn.value) return
  const { data } = await powerBankApi.getOrderConsumeType({
    deviceSn: deviceSn.value
  })
  configDetails.value = data?.orderConsumeTypeConfig?.configDetails
  selectedConfig.value = configDetails.value[0] || {}
  userBalance.value = data?.userBalance
  if (data?.cards.length) {
    selectedConfig.value = configDetails.value[1] || {}
    cards.value = data.cards
    useTimesAmount.value = 0
    for (let i = 0; i < data.cards.length; i++) {
      const { maxCount, usedCount } = data.cards[i]
      useTimesAmount.value += maxCount - usedCount
    }

  }
}
async function getConsumeInfo() {
  const { data } = await powerBankApi.getCustomerInfo()
  userBalance.value = data?.washCustomer?.balance || 0
}
const submit = () => {
  // if (userBalance.value == 0) {
  //   uni.showToast({
  //     title: '余额不足,请充值',
  //     icon: 'none'
  //   })
  //   return
  // }
  const { type } = selectedConfig.value
  switch (type) {
    case 2:
      start()
      break
    case 3:
      const card = cards.value[0]
      start({
        cardId: card?.id,
      })
      break
    default:
      break
  }
}
function jump() {
  uni.navigateTo({
    url: '/packageB/pages/carWash/mine'
  })
}

// 获取进行中的订单
const orders = ref()
async function getOrderInProgress() {
  if (!deviceSn.value) return
  const { data } = await powerBankApi.getCustomerWashingOrders({
    serviceType: serviceType.value
  })
  data.forEach(
    (item: {
      serviceType: any
      text: string
      deviceDetail: { site: { name: any } }
    }) => {
      switch (item?.washOrder?.serviceType) {
        case 1:
          item.text = `洗车机使用中！-${item.deviceDetail?.site?.name}-点击结束洗车后可停止计费。`
          break
        default:
          item.text = `设备使用中！-${item.deviceDetail?.site?.name}`
          break
      }
    }
  )
  orders.value = data
}
const env = ref('')
async function queryStart() {
  const { data } = await powerBankApi.queryScoreServiceOrder({
    outOrderNo: outOrderNo.value,
    paymentSubType: paymentSubType.value
  })
  if (data?.state === 'DOING') {
    start()
  } else {
    uni.showToast({
      icon: 'none',
      title: '支付分未授权'
    })
  }
}
async function refresh() {
  // const { origin, pathname, hash } = window.location
  // const href = `${origin + pathname + hash}`
  // window.location.href = href
  // location.reload()
}

// 充值 
const mask = ref(false)
const topUp = ref()
function openPopUp() {
  topUp.value.open()
}
function jumpToOrderDetail(orderObj?: { washOrder: { id: any } }) {
  if (!orderObj && orders.value.length) {
    orderObj = orders.value[orders.value.length - 1]
  }
  route({
    url: '/packageB/pages/carWash/washing',
    params: {
      orderId: orderObj?.washOrder?.id,
    }
  })
}
function toTopUp() {
  if (isBanner.value) {
    uni.showToast({
      title: 'APP内充值功能升级中,请使用微信或支付宝扫码充值',
      icon: 'none'
    })
    return
  }

  route({
    url: '/packageB/pages/carWash/topUp',
    params: {
      deviceSn: deviceSn.value,
      type: selectedConfig.value.type,
    }
  })
}


function openApp() {
  mask.value = false
  uni.showLoading({
    title: '正在打开APP'
  })
  setTimeout(() => {
    uni.hideLoading()
  }, 2000)
  launchClientApp(() => {
    mask.value = true
  })
}

// 会员卡
const cardParmas = reactive({
  id: '',
  createTime: '',
})
async function getCard() {
  if (!cardParmas.id || !cardParmas.createTime) return
  uni.showLoading()
  const { data } = await powerBankApi.getCard(cardParmas).finally(() => { uni.hideLoading() })
  if (data) {
    uni.showToast({
      title: '会员卡领取成功',
      icon: 'none'
    })
    route({
      url: '/packageB/pages/carWash/topUp'
    })
  }
}
onShow(async () => {
  if (userStore.hasLogin) {
    await getOrderInProgress()
    await getConsumeInfo()
    getMoney()
  }
})
const isBanner = ref(false)

// 提现提示
const showTips = ref(false)
async function getMoney() {
  const walletRuleId = 1 // 余额钱包id
  if (hasLogin.value) {
    const { data } = await moneyApi.walletList({ noPaging: true })
    const yueWallet = data.find(
      (item: { walletRuleId: number }) => item.walletRuleId === walletRuleId
    )
    if(yueWallet) {
      showTips.value = !!yueWallet.money
    }
  }
}
const showVideo = ref(false)
const toView = () => {
  // route({
  //   url: '/packageA/pages/shortVideo/index',
  //   params: {
  //     dynamicId: 455,
  //     type: 'preview',
  //   }
  // })
  showVideo.value = true
}

onLoad(async (option) => {
  if (option?.deviceSn) {
    deviceSn.value = option?.deviceSn
  }
  if (option?.serviceType) {
    serviceType.value = option?.serviceType
  }
  if (option?.isBanner) {
    isBanner.value = Boolean(option.isBanner)
  }
  console.log('deviceSn==>', deviceSn.value)
  console.log('serviceType==>', serviceType.value)
  const isApp = option?.from || browserVersion().isHeiyin
  console.log('isApp==>', isApp)
  if (option?.id) {
    cardParmas.id = option.id
  }
  if (option?.createTime) {
    cardParmas.createTime = option.createTime
  }

  if (isApp) {
    mask.value = !isBanner.value
    // #ifdef H5
    console.log('前端注册回调时机==>', new Date())
    window.JSBridge.registerEvent('HYUserEvent', async () => {
      await getDetail()
      await getOrderInProgress()
      await getOrderConsumeType()
      await getConsumeInfo()
      await getCard()
    })
    window.JSBridge.registerEvent(
      'deviceStart',
      (data: { outOrderNo: string }) => {
        outOrderNo.value = data.outOrderNo
        queryStart()
      }
    )
    env.value = 'app'
    paymentSubType.value = 1
    // #endif
  } else {
    if (browserVersion().mobile && !configStore.isWeChatBrowser) {
      // 非微信浏览器端不请求接口了，只作为打开app的入口
      // mask.value = true
      // return
    }
    await getDetail()
    await getOrderInProgress()
    await getOrderConsumeType()
    await getConsumeInfo()
    await getCard()
    // mask.value = true // 李总的需求，只通过APP扫码取设备
  }
  // #ifdef H5
  const { origin, hash } = location
  uni.setStorageSync('callback_return_url', origin + hash)
  // #endif
})
</script>
<template>
  <view class="container">
    <view class="topBox">
      <view class="action">
        <u-icon color="#fff" :size="40" name="reload" @click="refresh"></u-icon>
        <view class="mine" @click="jump">
          <u-image width="50rpx" height="50rpx"
            src="https://image.blacksilverscore.com/uploads/6844def4-1bf8-40ce-8995-a0043bf8e5cf.png"></u-image>
        </view>
      </view>
      <!-- <view class="tit">{{ siteInfo.name }}</view> -->
      <view class="tit">设备编号：{{ deviceSn }}</view>
      <view class="desc" v-if="siteInfo.parkingFeeDesc">（{{ siteInfo.parkingFeeDesc }}）</view>
      <view class="wrap">
        <view>设备使用说明：</view>
        <view>1.设备启动后冲水、泡沫或吸尘开始计费</view>
        <view>2.使用完毕后在设备上或者小程序上关闭设备结束计费</view>
        <!-- <view>计费规则：</view>
        <view>1.前24小时免费，超过24小时后2元一个小时</view>
        <view>2.总封顶99元</view> -->
      </view>
    </view>
    <!-- <view class="section">
      <view class="tit">支付方式说明</view>
      <view> 余额:余额中扣除费用 </view>
      <view> 优惠券:优惠券在洗车过程中会被优先抵扣使用 </view>
    </view> -->
    <view class="img_box">
      <image src="https://image.blacksilverscore.com/uploads/a72772e5-fa9d-411a-8035-4666e3caba57.png" mode="scaleToFill"
        class="img" />
    </view>
    <view class="selector" @click="showSelect">
      <view>{{ selectedConfig.name }}</view>
      <u-icon name="arrow-down" color="#666"></u-icon>
    </view>
    <u-select v-model="show" label-name="name" value-name="type" :list="configDetails" @confirm="confirm"></u-select>
    <view>
      <u-cell-item v-if="selectedConfig?.type !== 3" title="可用余额" :border-bottom="false"
        :value="(userBalance || '0') + '元'" :value-style="{ color: 'red' }" :arrow="false" @click="toTopUp">
        <template v-slot:right-icon>
          <text style="margin-left: 20rpx">去充值</text>
          <u-icon name="arrow-right" color="#666" size="26"></u-icon>
        </template>
      </u-cell-item>
      <u-cell-item v-else :title="`可用次数(${cards[0]?.title || 0})`" :border-bottom="false"
        :value="(useTimesAmount || '0') + '次'" :value-style="{ color: 'red' }" :arrow="false" @click="toTopUp">
        <template v-slot:right-icon>
          <text style="margin-left: 20rpx">去充值</text>
          <u-icon name="arrow-right" color="#666" size="26"></u-icon>
        </template>
      </u-cell-item>
    </view>

    <c_topUp ref="topUp" :config="selectedConfig?.config" :device="deviceInfo" />
    <view class="btn_wrap">
      <view class="order_tips" v-for="(item, index) in orders" :key="index" @click="jumpToOrderDetail(item)">
        <u-notice-bar mode="horizontal" :list="[item.text]" :volume-icon="false" :more-icon="true"></u-notice-bar>
      </view>
      <u-button ripple :hair-line="false" class="btn" :custom-style="{ background: '#50939c', color: '#fff' }"
        @click="jumpToOrderDetail(null)" v-if="orders?.length > 0">
        <view flex style="align-items: center;">
          <text mr1>点击查看进行中的洗车</text>
          <u-icon name="arrow-right" color="#fff" size="26"></u-icon>
        </view>
      </u-button>
      <u-button v-else ripple :hair-line="false" class="btn" :custom-style="{ background: '#50939c', color: '#fff' }"
        @click="submit" :loading="loading" :disabled="orders?.length > 0 || isBanner">点击开始洗车</u-button>
    </view>
    <view class="withdrawTips" v-if="showTips" @click="toView">
      您的洗车补贴已到账！
      点击查看领取方式 <text class="pointer"> 👈</text>
    </view>
    <u-popup v-model="mask" :mask-close-able="false" :border-radius="12" mode="center" width="400rpx" height="280rpx">
      <view class="mask_tips"> APP正在升级，请使用微信或支付宝扫码洗车 </view>
      <!-- <view class="mask_tips"> 请使用黑银APP扫码洗车 </view> -->
      <!-- <view v-if="isWeChat()" style="padding:0 20rpx">（点击右上角"...",在手机自带浏览器打开，按提示下载）</view> -->
      <!-- <view v-else class="open_app" @click="openApp"> 打开黑银APP <u-icon name="arrow-right" size="28" color="blue"></u-icon> </view> -->
    </u-popup>
    <u-popup :closeable="true" v-model="showVideo" :border-radius="12" mode="center" width="100%" height="auto">
      <video style="width: 100%;display: block;" controls poster="https://image.blacksilverscore.com/App/ecf9936a-2a42-45e9-947c-6bf79eaad1cb.mp4?x-oss-process=video/snapshot,t_3000,f_jpg,w_540,ar_auto" src="https://image.blacksilverscore.com/App/ecf9936a-2a42-45e9-947c-6bf79eaad1cb.mp4"></video>
    </u-popup>
  </view>
</template>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #fff;

  .topBox {
    background: #50939c;
    padding: 40rpx;

    .tit {
      font-size: 36rpx;
      color: #fff;
    }

    .desc {
      color: #fff;
      margin-top: 10rpx;
    }

    .wrap {
      background: rgba(255, 255, 255, 0.4);
      border-radius: 20rpx;
      color: #fff;
      padding: 10rpx 20rpx;
      line-height: 44rpx;
      margin-top: 20rpx;
      font-size: 26rpx;
    }

    .action {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10rpx;
      align-items: center;
    }
  }

  .section {
    padding: 30rpx;
    line-height: 50rpx;
  }

  .img_box {
    .img {
      width: 100%;
      margin-top: 100rpx;
    }
  }
}

.selector {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid #ccc;
  border-radius: 8rpx;
  padding: 20rpx 0;
  gap: 10rpx;
  margin: 20rpx 30rpx 0 30rpx;
}

.btn_wrap {
  margin: 30rpx 30rpx 0 30rpx;
  padding-bottom: 80rpx;

  .btn {
    // position: absolute;
    bottom: 0;
    left: 0;
    // width: 100%;
    height: 100rpx;
    border-radius: 20rpx;
  }

  :deep(.u-btn--default--disabled) {
    opacity: 0.5;
  }

  .order_tips {
    margin-bottom: 30rpx;
  }
}

.check {
  text-align: center;
  margin-top: 30rpx;
  font-size: 24rpx;
}

.mask_tips {
  text-align: center;
  font-size: 30rpx;
  font-weight: bold;
  margin-top: 60rpx;
}

.open_app {
  margin-top: 30rpx;
  text-align: center;
  color: blue;
}

.tips {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 30rpx;
}

.withdrawTips {
  animation: shake 0.5s;
  animation-iteration-count: 2;
  padding-bottom: 50rpx;
  @keyframes shake {
    0% {
      transform: translate(1px, 1px) rotate(0deg);
    }

    10% {
      transform: translate(-1px, -2px) rotate(-1deg);
    }

    20% {
      transform: translate(-3px, 0px) rotate(1deg);
    }

    30% {
      transform: translate(3px, 2px) rotate(0deg);
    }

    40% {
      transform: translate(1px, -1px) rotate(1deg);
    }

    50% {
      transform: translate(-1px, 2px) rotate(-1deg);
    }

    60% {
      transform: translate(-3px, 1px) rotate(0deg);
    }

    70% {
      transform: translate(3px, 1px) rotate(-1deg);
    }

    80% {
      transform: translate(-1px, -1px) rotate(1deg);
    }

    90% {
      transform: translate(1px, 2px) rotate(0deg);
    }

    100% {
      transform: translate(1px, -2px) rotate(-1deg);
    }
  }
  text-align: center;
  color: #50939c;

  // 给pointer添加手指左右滑动的动画
  @keyframes hand {
    0% {
      transform: translateX(0);
    }

    50% {
      transform: translateX(-5px);
    }

    100% {
      transform: translateX(0);
    }
  }

  .pointer {
    display: inline-block;
    margin-left: 5px;
    animation: hand 1s infinite;
  }
}</style>
